package vl07.network;

import java.awt.BorderLayout;
import java.awt.Container;
import java.io.*;
import java.net.*;
import javax.swing.*;

public class Browser1 extends JFrame {
	private JLabel lblUrl;
	private JTextField txtUrl;
	private JButton btnGo;
	private JScrollPane paneInhalt;
	private JTextArea txtInhalt;

	public static void main(String[] args) {
		new Browser1();
	}

	/** Creates new form Browser1 */
	public Browser1() {
		super("Browser1");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLayout(new BorderLayout());
		
		Box topBox = Box.createHorizontalBox();
		this.add(topBox, BorderLayout.NORTH);
		
		lblUrl = new JLabel("URL");
		lblUrl.setText("URL");
		topBox.add(lblUrl);

		txtUrl = new JTextField();
		txtUrl.setText("http://www.google.com/");
		txtUrl.setPreferredSize(new java.awt.Dimension(400, 21));
		topBox.add(txtUrl);

		topBox.add(Box.createHorizontalStrut(30));
		
		btnGo = new JButton("Go");
		topBox.add(btnGo);
		btnGo.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				browse();
			}
		});

		paneInhalt = new JScrollPane();
		paneInhalt.setPreferredSize(new java.awt.Dimension(600, 300));
		txtInhalt = new JTextArea();
		txtInhalt.setFont(new java.awt.Font("Courier New", 0, 12));
		paneInhalt.setViewportView(txtInhalt);
		this.add(paneInhalt, BorderLayout.CENTER);

		pack();
		setVisible(true);
	}

	private void browse() {
		URL url;
		BufferedReader inReader = null;
		String lineIn;
		StringBuffer urlInhalt = new StringBuffer();

		// Network errors are always possible
		try {
			// Create a new URL-Object
			url = new URL(txtUrl.getText());

			// Set up the reader classes
			InputStream in1 = url.openStream();
			InputStreamReader in2 = new InputStreamReader(in1);
			inReader = new BufferedReader(in2);
			
			// Read the URL contents
			while ((lineIn = inReader.readLine()) != null) {
				urlInhalt.append(lineIn + "\n");
			}

			// Show the result in "txtInhalt"
			txtInhalt.setText(urlInhalt.toString());
		}

		// If an error occurred, show the error message in txtInhalt
		catch (Exception err) {
			txtInhalt.setText("ERROR: " + err.toString());
		}
		finally {
			try {
				if (inReader != null) inReader.close();
			} catch (IOException e) {
			}
		}
	}
}
